import React, { useState, useEffect } from 'react'
import './index.scss'

interface TodoItem {
    id: string
    text: string
    completed: boolean
    priority: 'low' | 'medium' | 'high'
    createdAt: string
    dueDate?: string
}

const TodoList: React.FC = () => {
    // 使用useState Hook来管理待办事项列表、输入框的值、过滤器和优先级状态
    const [todos, setTodos] = useState<TodoItem[]>([]) 
    const [inputValue, setInputValue] = useState('')
    const [filter, setFilter] = useState<'all' | 'active' | 'completed'>('all')
    const [priority, setPriority] = useState<'low' | 'medium' | 'high'>('medium')
    const [dueDate, setDueDate] = useState('')

    // 在组件挂载后，初始化示例待办事项数据
    useEffect(() => {
        const initialTodos: TodoItem[] = [
            // 示例待办事项数据
            {
                id: '1',
                text: '完成新人成长地图知识库',
                completed: true,
                priority: 'low',
                createdAt: new Date().toISOString(),
                dueDate: '2025-08-29'
            },
            {
                id: '2',
                text: '代码审查',
                completed: true,
                priority: 'medium',
                createdAt: new Date().toISOString()
            },
            {
                id: '3',
                text: '组件配置调研',
                completed: false,
                priority: 'high',
                createdAt: new Date().toISOString(),
                dueDate: '2025-09-05'
            }
        ]
        setTodos(initialTodos)
    }, [])

    // 添加新的待办事项
    const addTodo = () => {
        if (inputValue.trim()) {
            const newTodo: TodoItem = {
                id: Date.now().toString(),
                text: inputValue.trim(),
                completed: false,
                priority,
                createdAt: new Date().toISOString(),
                dueDate: dueDate || undefined
            }
            // 将新待办事项添加到列表的开头
            setTodos([newTodo,...todos])
            // 清空输入框和截止日期选择器
            setInputValue('')
            setDueDate('')
        }
    }

    // 切换待办事项的完成状态
    const toggleTodo = (id: string) => {
        setTodos(todos.map(todo =>
            todo.id === id? {...todo, completed:!todo.completed } : todo
        ))
    }

    // 删除指定的待办事项
    const deleteTodo = (id: string) => {
        setTodos(todos.filter(todo => todo.id!== id))
    }

    // 编辑指定的待办事项的文本内容
    const editTodo = (id: string, newText: string) => {
        setTodos(todos.map(todo =>
            todo.id === id? {...todo, text: newText } : todo
        ))
    }

    // 根据过滤器状态过滤待办事项列表
    const filteredTodos = todos.filter(todo => {
        switch (filter) {
            case 'active':
                return!todo.completed
            case 'completed':
                return todo.completed
            default:
                return true
        }
    })

    // 根据优先级返回相应的颜色
    const getPriorityColor = (priority: string) => {
        switch (priority) {
            case 'high':
                return '#ff4d4f'
            case 'medium':
                return '#faad14'
            case 'low':
                return '#52c41a'
            default:
                return '#d9d9d9'
        }
    }

    // 将日期字符串格式化为中文日期格式
    const formatDate = (dateString: string) => {
        return new Date(dateString).toLocaleDateString('zh-CN')
    }

    // 判断待办事项是否已过期
    const isOverdue = (dueDate?: string) => {
        if (!dueDate) return false
        return new Date(dueDate) < new Date()
    }

    return (
        <div className="todo-container">
            <div className="todo-header">
                <h2>待办事项</h2>
                <div className="todo-stats">
                    <span>总计: {todos.length}</span>
                    <span>已完成: {todos.filter(t => t.completed).length}</span>
                    <span>待完成: {todos.filter(t =>!t.completed).length}</span>
                </div>
            </div>

            <div className="todo-input-section">
                <div className="input-row">
                    <input
                        type="text"
                        value={inputValue}
                        onChange={(e) => setInputValue(e.target.value)}
                        placeholder="添加新的待办事项..."
                        className="todo-input"
                        onKeyPress={(e) => e.key === 'Enter' && addTodo()}
                    />
                    <select
                        value={priority}
                        onChange={(e) => setPriority(e.target.value as 'low' | 'medium' | 'high')}
                        className="priority-select"
                    >
                        <option value="low">低优先级</option>
                        <option value="medium">中优先级</option>
                        <option value="high">高优先级</option>
                    </select>
                </div>
                <div className="input-row">
                    <input
                        type="date"
                        value={dueDate}
                        onChange={(e) => setDueDate(e.target.value)}
                        className="date-input"
                    />
                    <button onClick={addTodo} className="add-btn">
                        添加
                    </button>
                </div>
            </div>

            <div className="todo-filters">
                <button
                    className={filter === 'all'? 'active' : ''}
                    onClick={() => setFilter('all')}
                >
                    全部
                </button>
                <button
                    className={filter === 'active'? 'active' : ''}
                    onClick={() => setFilter('active')}
                >
                    待完成
                </button>
                <button
                    className={filter === 'completed'? 'active' : ''}
                    onClick={() => setFilter('completed')}
                >
                    已完成
                </button>
            </div>

            <div className="todo-list">
                {filteredTodos.length === 0? (
                    <div className="empty-state">
                        {filter === 'all'? '暂无待办事项' : `暂无${filter === 'active'? '待完成' : '已完成'}的事项`}
                    </div>
                ) : (
                    filteredTodos.map(todo => (
                        <TodoItemComponent
                            key={todo.id}
                            todo={todo}
                            onToggle={toggleTodo}
                            onDelete={deleteTodo}
                            onEdit={editTodo}
                            getPriorityColor={getPriorityColor}
                            formatDate={formatDate}
                            isOverdue={isOverdue}
                        />
                    ))
                )}
            </div>
        </div>
    )
}

interface TodoItemProps {
    todo: TodoItem
    onToggle: (id: string) => void
    onDelete: (id: string) => void
    onEdit: (id: string, text: string) => void
    getPriorityColor: (priority: string) => string
    formatDate: (date: string) => string
    isOverdue: (date?: string) => boolean
}

const TodoItemComponent: React.FC<TodoItemProps> = ({
    todo,
    onToggle,
    onDelete,
    onEdit,
    getPriorityColor,
    formatDate,
    isOverdue
}) => {
    const [isEditing, setIsEditing] = useState(false)
    const [editText, setEditText] = useState(todo.text)

    const handleEdit = () => {
        if (editText.trim() && editText !== todo.text) {
            onEdit(todo.id, editText.trim())
        }
        setIsEditing(false)
    }

    const handleCancel = () => {
        setEditText(todo.text)
        setIsEditing(false)
    }

    return (
        <div className={`todo-item ${todo.completed ? 'completed' : ''} ${isOverdue(todo.dueDate) && !todo.completed ? 'overdue' : ''}`}>
            <div className="todo-content">
                <div className="todo-main">
                    <input
                        type="checkbox"
                        checked={todo.completed}
                        onChange={() => onToggle(todo.id)}
                        className="todo-checkbox"
                    />
                    <div
                        className="priority-indicator"
                        style={{ backgroundColor: getPriorityColor(todo.priority) }}
                    />
                    {isEditing ? (
                        <input
                            type="text"
                            value={editText}
                            onChange={(e) => setEditText(e.target.value)}
                            onKeyPress={(e) => e.key === 'Enter' && handleEdit()}
                            onBlur={handleEdit}
                            className="edit-input"
                            autoFocus
                        />
                    ) : (
                        <span
                            className="todo-text"
                            onDoubleClick={() => setIsEditing(true)}
                        >
                            {todo.text}
                        </span>
                    )}
                </div>
                <div className="todo-meta">
                    {todo.dueDate && (
                        <span className={`due-date ${isOverdue(todo.dueDate) && !todo.completed ? 'overdue' : ''}`}>
                            截止: {formatDate(todo.dueDate)}
                        </span>
                    )}
                    <span className="created-date">
                        创建: {formatDate(todo.createdAt)}
                    </span>
                </div>
            </div>
            <div className="todo-actions">
                {isEditing ? (
                    <>
                        <button onClick={handleEdit} className="save-btn">保存</button>
                        <button onClick={handleCancel} className="cancel-btn">取消</button>
                    </>
                ) : (
                    <>
                        <button onClick={() => setIsEditing(true)} className="edit-btn">编辑</button>
                        <button onClick={() => onDelete(todo.id)} className="delete-btn">删除</button>
                    </>
                )}
            </div>
        </div>
    )
}

export default TodoList